package com.duanjc.mergemd.task;

import cn.hutool.core.io.FileUtil;
import com.duanjc.mergemd.utils.FileCheckUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * [一句话描述该类的功能]
 *
 * @author : [duanjiangcheng]
 * @version : [v1.0]
 * @createTime : [2022/11/25 10:09]
 */
@Slf4j
@Service
public class MergeTask {


    /**
     * description: 分片合并 <br>
     * version: 1.0 <br>
     * date: 2022/11/25 11:06 <br>
     * author: duanjiangcheng <br>
     * @param list list
     * @param out out
     * @param suffix suffix
     * @param downLatch downLatch
     * @return void
     */
    @Async
    public void partitionMerge(List<File> list, File out, String suffix, CountDownLatch downLatch) {
        log.info("线程-" + Thread.currentThread().getName() + ":正在进行分片导出！");
        mergeToOne(list, out, suffix);
        downLatch.countDown();
    }

    /*public void insertToDirectory(BufferedWriter bufferedWriter, File dest) throws IOException {
        fileCount--;
        if (0 == fileCount) {
            bufferedWriter.write("[TOC]\n");
        }
    }*/
    
    /**
     * description: catalogMerge <br>
     * version: 1.0 <br>
     * date: 2022/11/28 16:44 <br>
     * author: duanjiangcheng <br>
     * @param srcPath
     * @param output
     * @param suffix
     * @param level
     * @param downLatch
     * @return void
     */ 
    //@Async
    public void catalogMerge(String srcPath, String output, String suffix, int level, CountDownLatch downLatch) {
        mergeCatalog(srcPath, output, suffix, null, level - 1);
        downLatch.countDown();
    }

    @Async
    public void catalogMerge(File srcPath, String suffix, int level, CountDownLatch downLatch) {

    }


    /**
     * description: 合并一个文件 <br>
     * version: 1.0 <br>
     * date: 2022/11/25 13:55 <br>
     * author: duanjiangcheng <br>
     * @param list list
     * @param out out
     * @param suffix suffix
     * @return void
     */
    private void mergeToOne(List<File> list, File out, String suffix) {
        BufferedWriter bufferedWriter = null;
        try {
            bufferedWriter = FileUtil.getWriter(out, StandardCharsets.UTF_8, true);

            for (File file : list) {
                String fileName = file.getName();
                if (FileCheckUtils.matches(fileName, suffix)) {
                    BufferedReader bufferedReader = FileUtil.getUtf8Reader(file);
                    String line = null;
                    try {
                        //insertToDirectory(bufferedWriter, out);
                        while ((line = bufferedReader.readLine()) != null) {
                            bufferedWriter.write(line);
                            bufferedWriter.newLine();
                        }
                        bufferedWriter.newLine();
                        bufferedWriter.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            bufferedReader.close();
                        } catch (IOException e) {
                            log.error("关闭输入流失败！", e);
                        }
                    }
                }
            }
        } finally {
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                log.error("关闭输出流失败！", e);
            }
        }
    }

    private void mergeCatalog(String srcPath,String output, String suffix, File out, int level) {

        if (level == 0) {
            List<File> list = FileUtil.loopFiles(srcPath).stream()
                    .filter(i -> suffix.replace(".", "").equals(FileUtil.getSuffix(i)))
                    .collect(Collectors.toList());
            if (list.size() > 1) {
                if(out == null){
                    out = FileUtil.touch(srcPath + suffix);
                }
                mergeToOne(list, out, suffix);
                //移动到out目录下
                File outDirectory = new File(output);
                if (!FileUtil.isDirectory(outDirectory) || FileUtil.exist(outDirectory)) {
                    FileUtil.mkdir(outDirectory);
                }
                FileUtil.move(out, outDirectory, true);
            }
        } else if (FileUtil.isDirectory(new File(srcPath))) {
            File[] files = FileUtil.ls(srcPath);

            //创建合并文件
            for (File f : files) {
                if (!FileUtil.isDirectory(f) || suffix.replace(".", "").equals(FileUtil.getSuffix(f))) {
                    continue;
                }
                if (level == 1) {
                    File newFile = FileUtil.touch(f.getPath() + suffix);
                    mergeCatalog(f.getPath(),output, suffix, newFile, level - 1);
                } else if (level > 1) {
                    mergeCatalog(f.getPath(),output, suffix, null, level - 1);
                }

            }
        }
    }

    /**
     * description: 复制图片 <br>
     * version: 1.0 <br>
     * date: 2022/11/29 10:14 <br>
     * author: duanjiangcheng <br>
     * @param src
     * @param output
     * @return int
     */
    public int copyPic(String src, String output) {

        List<String> picType = new ArrayList<>();
        picType.add("png");
        picType.add("jpg");
        picType.add("jpeg");
        List<File> list = FileUtil.loopFiles(src).stream()
                .filter(i -> picType.contains(FileUtil.getSuffix(i)))
                .collect(Collectors.toList());


        File out = FileUtil.mkdir(output + FileUtil.FILE_SEPARATOR + "images");

        list.forEach(i -> FileUtil.copy(i, out, true));
        return list.size();
    }
}
